<template>
	<view class="content">
		<view class="" v-for="item in deviceList" :key="item.deviceId"
			style="border-bottom: 1px solid #000;padding: 10px;" @click="createBLEConnection(item.deviceId)">
			<view class="">
				{{item.name}}
			</view>
			<view class="">
				{{item.deviceId}}
			</view>
		</view>
		<button @click="ztandbf">暂停/播放</button>
		<button @click="shang">上一首</button>
		<button @click="xia">下一首</button>
		<button @click="dingshi">定时数据</button>
		<view class="" v-if="mp3Total">
			总时长:{{mp3Total}}
		</view>
		<view class="" v-if="schedule">
			进度:{{schedule}}
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				discovering: false, //蓝牙是否处于搜索状态
				deviceList: [], //设备列表 
				deviceId: '', //已连接的蓝牙设备
				Connecting: false, // 蓝牙连接状态
				serviceUUID: '', //蓝牙服务的UUID
				writeUUid: '', //写入UUID
				notifyUUid: '', //广播UUID
				writeBleOriginalValue: [85, 176, 0],
				mp3Total: '',
				schedule:''
			}
		},
		methods: {
			seachDevice() {
				if (!this.discovering) {
					this.openBluetoothAdapter();
					if (this.Connecting) {
						this.closeBLEConnect(this.deviceId);
					}
				} else {
					this.Toast("正在扫描中，请等待");
				}

			},
			//检查蓝牙打开，初始化蓝牙
			openBluetoothAdapter() {
				uni.openBluetoothAdapter({
					success: (res) => {
						//初始化成功,搜索设备
						setTimeout(() => {
							this.deviceList = []; //每次扫描清空设备列表，不然会导致重复
							this.startBluetoothDeviceDiscovery();
						}, 100);
						//定时关闭搜索设备
						setTimeout(() => {
							this.stopBluetoothDevicesDiscovery();
						}, 15 * 1000);
					},
					fail: err => {
						uni.showToast({
							title: '请确认手机蓝牙是否打开'
						})
					}
				})
			},
			//这里是开启蓝牙搜寻  
			startBluetoothDeviceDiscovery() {
				uni.startBluetoothDevicesDiscovery({
					// services: ["0000FFC0","0000","1000","8000","00805F9B34FB"],
					services: ["0000FFC0"],
					success: (resd) => {
						console.log("打开成功", resd);
					},
					fail: err => {
						console.error("startBluetoothDevicesDiscoveryErr", err);
						this.Toast("请检查蓝牙状态")
					}
				})
			},
			//关闭蓝牙搜索
			stopBluetoothDevicesDiscovery() {
				uni.stopBluetoothDevicesDiscovery({
					success: res => {

					}
				})
			},

			//监听连接状态
			onBLEConnectionStateChange() {
				uni.onBLEConnectionStateChange(res => {
					console.log(`设备 ${res.deviceId},connected: ${res.connected}`)
					this.Connecting = res.connected;
					this.deviceId = res.deviceId;
				})
			},
			/*连接低功耗蓝牙设备
			  @params deviceId  蓝牙设备id
			  0	ok	正常
			  10000	not init	未初始化蓝牙适配器
			  10001	not available	当前蓝牙适配器不可用
			  10002	no device	没有找到指定设备
			  10003	connection fail	连接失败
			  10004	no service	没有找到指定服务
			  10005	no characteristic	没有找到指定特征值
			  10006	no connection	当前连接已断开
			  10007	property not support	当前特征值不支持此操作
			  10008	system error	其余所有系统上报的异常
			  10009	system not support	Android 系统特有，系统版本低于 4.3 不支持 BLE
			*/
			createBLEConnection(deviceId) {
				if (this.discovering) {
					this.stopBluetoothDevicesDiscovery()
				}
				if (this.Connecting) {
					this.Toast("设备已连接");
					return
				}
				uni.showLoading({
					title: "连接设备中..."
				})
				uni.createBLEConnection({
					deviceId,
					success: res => {
						uni.hideLoading();
						this.Toast('设备连接成功')
						this.deviceId = deviceId;
						//获取蓝牙服务
						setTimeout(() => {
							this.getBLEDeviceServices(deviceId);
						}, 1500)

					},
					fail: err => {
						uni.hideLoading();
						this.Toast('设备连接失败,请检查重试')
						if (err.errCode == -1) {
							this.closeBLEConnect(deviceId)
						}
					}
				})
			},
			/*获取蓝牙设备所有服务(service)。
			  连接蓝牙后调用
			 @parmas deviceId  蓝牙设备id
			*/
			getBLEDeviceServices(deviceId) {
				const _this = this;
				uni.getBLEDeviceServices({
					deviceId,
					success: res => {
						//获取特征值
						console.log(res.services);
						let services = res.services;
						_this.serviceUUID = services[0].uuid;
						this.getBLEDeviceCharacteristics(deviceId, _this.serviceUUID).then(res => {
							console.log(res);
							_this.notifyUUid = res.characteristics[0].uuid
							_this.writeUUid = res.characteristics[1].uuid
							uni.notifyBLECharacteristicValueChange({
								deviceId: deviceId,
								serviceId: _this.serviceUUID,
								characteristicId: _this.notifyUUid,
								state: true,
								success: (res) => {
									console.log("广播开启成功")
									_this.onBLECharacteristicValueChange();
								},
								fail: (err) => {
									console.error(err)
								}
							})
							setTimeout(() => {
								// _this.writeBLECharacteristicValue([0x5A, 0x03, 0xFF])
							}, 2000)
						})


					},
					fail: err => {
						console.warn("设备服务Error" + err)
					}
				})
			},
			ztandbf() {
				console.log(111);
				this.handlerVal(this.writeBleOriginalValue.concat([1, 3]))
				// this.writeBLECharacteristicValue([0x55, 0xB0, 0x00, 0x01, 0x03, 0x09, 0x01])
			},
			shang() {
				console.log('shang');
				this.handlerVal(this.writeBleOriginalValue.concat([1, 1]))
				// this.writeBLECharacteristicValue([0x55, 0xB0, 0x00, 0x01, 0x01, 0x07, 0x01])
			},
			xia() {
				console.log('xia');
				this.handlerVal(this.writeBleOriginalValue.concat([1, 2]))
				// this.writeBLECharacteristicValue([0x55, 0xB0, 0x00, 0x01, 0x02, 0x08, 0x01])
			},
			dingshi() {
				console.log('dingshi');
				this.handlerVal(this.writeBleOriginalValue.concat([1, 0]))
				// this.writeBLECharacteristicValue([0x55, 0xB0, 0x00, 0x01, 0x00, 0x0C, 0x01])
			},
			handlerVal(val) {
				let count = val.reduce((prev, cur, index, arr) => {
					return prev + cur
				}, 0)
				this.writeBLECharacteristicValue(val.concat([count % 256, count >> 8]))
			},
			/*向蓝牙设备中写入数据
			    @parmas  deviceId 蓝牙设备 id
				@parmas	 serviceId	蓝牙特征值对应服务的 uuid
				@parmas  characteristicId 蓝牙特征值的 uuid
				@parmas	 value	ArrayBuffer	蓝牙设备特征值对应的二进制值
			*/
			writeBLECharacteristicValue(value) {
				console.log(this.writeBleOriginalValue);
				console.log(value);
				// 向蓝牙设备发送一个0x00的16进制数据
				const array = new Uint8Array(value)
				// 55 b0 00 03 09 01 29 3b 01
				// 55 b0 00 03 09 00 b2 c3 01

				// 55 b0 00 03 07 00 08 17 01
				console.log(array.buffer);
				console.log('deviceId:', this.deviceId)
				console.log('serviceId:', this.serviceUUID, )
				console.log('characteristicId:', this.writeUUid)
				uni.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: this.serviceUUID,
					characteristicId: this.writeUUid,
					value: array.buffer,
					success: res => {
						console.log("写入成功", res)
						uni.showToast({
							icon: 'success',
							title: "写入成功"
						})
					},
					fail: err => {
						console.error("写入失败", err)
						uni.showToast({
							icon: 'error',
							title: "写入失败"
						})
					}
				})
			},
			formateTime(time) {
				const h = parseInt(time / 3600)
				const minute = parseInt(time / 60 % 60)
				const second = Math.ceil(time % 60)
				const hours = h < 10 ? '0' + h : h
				const formatSecond = second > 59 ? 59 : second
				return `${hours > 0 ? `${hours}:` : ''}${minute < 10 ? '0' + minute : minute}:${formatSecond < 10 ? '0' + formatSecond : formatSecond}`
			},
			// 监测低功耗蓝牙设备变化
			onBLECharacteristicValueChange() {
				uni.onBLECharacteristicValueChange(res => {
					console.log(`监听低功耗蓝牙设备的特征值变化事件 ${res.characteristicId} has changed, now is ${res.value}`)
					console.log(this.ab2hex(res.value));
					const returnVal = this.ab2hex(res.value)
					if (returnVal[3] == 3 && returnVal[4] == 9) {
						this.mp3Total = this.formateTime(returnVal[5] * 256 + returnVal[6])
					}
					if (returnVal[3] == 3 && returnVal[4] == 7) {
						this.schedule = this.formateTime(returnVal[5] * 256 + returnVal[6])
					}
					
				})
			},
			ab2hex(buffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(buffer),
					function(bit) {
						return bit
					}
				)
				return hexArr
			},
			/*获取蓝牙设备某个服务中所有特征值(characteristic)。
			  @parmas deviceId 设备id
			  @parmas serviceId 蓝牙服务uuid ，需要使用getBLEDeviceServices 获取
			*/
			getBLEDeviceCharacteristics(deviceId, serviceId) {
				const _this = this;
				return new Promise((resolve, reject) => {
					uni.getBLEDeviceCharacteristics({
						deviceId,
						serviceId,
						success: res => {
							resolve(res);
						},
						fail: err => {
							console.log("获取特征值失败", err)
							reject(err);
						}
					})
				})
			},
			/*断开蓝牙设备连接
			  @params deviceId
			*/
			closeBLEConnect(deviceId) {
				uni.closeBLEConnection({
					deviceId,
					success: res => {
						this.deviceId = "";
						console.log("断开成功", res);
					},
					fail: err => {
						console.error("断开错误", err);
					}
				})
			},
			/*获取蓝牙设备信号强度 @parmas deviceId 设备id */
			getBLEDeviceRssi(deviceId) {
				uni.getBLEDeviceRSSI({
					deviceId,
					success: res => {
						console.log("获取蓝牙设备强度成功", res);
					},
					fail: err => {
						console.error("获取蓝牙强度失败,", err);
					}
				})
			},
			/*读取蓝牙设备特征值的二进制数据
			  @parmas deviceId  蓝牙设备Id
			  @params serviceId  蓝牙特征值 对应服务的uuid
			  @params characteristicId 蓝牙特征值的 uuid
			*/
			readBLEDeviceData(deviceId, serviceId, characteristicId) {
				uni.readBLECharacteristicValue({
					deviceId,
					serviceId,
					characteristicId,
					success: res => {
						console.log("读取设备值成功", res);
					},
					fail: err => {
						console.error("读取设备值err", err)
					}
				})
			},

			Toast(title) {
				uni.showToast({
					title,
					position: 'bottom',
					icon: 'none'
				})
			},
		},
		onLoad() {
			//监听蓝牙是否搜索
			uni.onBluetoothAdapterStateChange((res) => {
				console.log("蓝牙" + (res.discovering ? "开启" : "关闭") + "搜索")
				this.discovering = res.discovering;
			})
			//监听扫描到的蓝牙设备
			uni.onBluetoothDeviceFound(resd => {
				const devices = resd.devices[0];
				this.deviceList.push(devices)
				console.log(devices);
			})
			this.onBLEConnectionStateChange();
			this.seachDevice()
			// this.onBLECharacteristicValueChange()
		},
		onUnload() {
			if (this.discovering) {
				this.stopBluetoothDevicesDiscovery();
			}
			if (this.Connecting) {
				this.closeBLEConnect(this.deviceId);
			}
		},

	}
</script>

<style>
	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>